package com.alili_tv.system.utils;

import cn.hutool.core.util.IdUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

public class CacheUtils {

    private static final String loginCookieName = "AUTHORITY";

    /**
     * 持久化登录，设置cookie和redis缓存
     * @param userId
     * @param response
     * @param redisTemplate redisTemplate不能直接new，那就传入spring管理的
     */
    public static void setLoginCache(Long userId, HttpServletResponse response, RedisTemplate<String, Object> redisTemplate) {
        // 生成key
        String key = IdUtil.simpleUUID();

        Cookie cookie = new Cookie(loginCookieName, key);
        cookie.setPath("/");
        cookie.setMaxAge(60*60*24*3);
        response.addCookie(cookie);

        redisTemplate.opsForValue().set(key, userId, 3, TimeUnit.DAYS);
    }


    public static String getLoginCookie(HttpServletRequest request) {
        return getCookie(request, loginCookieName);
    }

    /**
     * 清除登录缓存（退出登录）
     * @param request
     * @param response
     * @param redisTemplate
     */
    public static void clearLoginCache(HttpServletRequest request,
                                       HttpServletResponse response,
                                       RedisTemplate<String, Object> redisTemplate) {
        String key = getLoginCookie(request);

        Cookie cookie = new Cookie(loginCookieName, null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        redisTemplate.delete(key);
    }

    /**
     * 获取指定cookie
     */
    public static String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (key.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return null;
    }

}
